<template>
  <div class="order-management">
    <!-- 搜索条件 -->
    <el-card class="search-card">
      <el-form
        :model="searchForm"
        label-width="100px"
        @submit.prevent="searchOrders"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="searchForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="searchForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否支付">
              <el-select
                v-model="searchForm.ispaid"
                placeholder="请选择支付状态"
                style="width: 100%"
              >
                <el-option label="全部" :value="null"></el-option>
                <el-option label="已支付" :value="1"></el-option>
                <el-option label="未支付" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="searchOrders">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="orders-card">
      <div class="order-list">
        <el-row :gutter="20">
          <el-col
            v-for="order in orders"
            :key="order.orderid"
            :span="24"
            class="order-item"
          >
            <el-card class="order-card">
              <el-row :gutter="20">
                <!-- 左侧汽车信息 -->
                <el-col :span="12">
                  <div class="car-info">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <div class="car-image">
                          <img :src="order.pictures" class="car-image" />
                        </div>
                      </el-col>
                      <el-col :span="16">
                        <div class="car-details" style="width: 150px">
                          <h3>{{ order.carname }}</h3>
                          <p>
                            <span class="label">订单ID:</span>
                            {{ order.orderid }}
                          </p>
                          <p>
                            <span class="label">车辆ID:</span> {{ order.cdid }}
                          </p>
                          <p>
                            <span class="label">车行:</span> {{ order.lname }}
                          </p>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>

                <!-- 右侧订单信息 -->
                <el-col :span="10">
                  <div class="order-details">
                    <el-descriptions :column="1" size="small" border>
                      <el-descriptions-item label="创建时间">
                        {{ formatDate(order.creattime) }}
                      </el-descriptions-item>
                      <el-descriptions-item label="结束时间">
                        {{ formatDate(order.endtime) }}
                      </el-descriptions-item>
                      <el-descriptions-item label="总价">
                        <span class="price">¥{{ order.totalprice }}</span>
                      </el-descriptions-item>
                      <el-descriptions-item label="支付状态">
                        <el-tag
                          :type="order.ispaid === 1 ? 'success' : 'danger'"
                        >
                          {{ order.ispaid === 1 ? "已支付" : "未支付" }}
                        </el-tag>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </el-col>

                <!-- 操作列 -->
                <el-col :span="2">
                  <div class="order-actions">
                    <el-button
                      type="primary"
                      :icon="Edit"
                      circle
                      @click="openEditDialog(order)"
                      title="修改订单"
                    />
                    <el-button
                      type="danger"
                      :icon="Delete"
                      circle
                      @click="deleteOrder(order)"
                      title="删除订单"
                      style="margin-top: 10px"
                    />
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 修改订单对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改订单时间"
      width="500px"
      :before-close="handleClose"
    >
      <el-form :model="editForm" label-width="100px" ref="editFormRef">
        <el-form-item label="订单ID">
          <el-input v-model="editForm.orderid" disabled />
        </el-form-item>
        <el-form-item label="开始时间" prop="creattime" required>
          <el-date-picker
            v-model="editForm.creattime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endtime" required>
          <el-date-picker
            v-model="editForm.endtime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrder">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Delete, Picture } from "@element-plus/icons-vue";
import api from "@/util/service";
// 搜索表单
const searchForm = reactive({
  startTime: null,
  endTime: null,
  ispaid: null,
});

// 订单数据
const orders = ref([]);

// 编辑对话框
const editDialogVisible = ref(false);
const editFormRef = ref();
const editForm = reactive({
  orderid: "",
  creattime: "",
  endtime: "",
});

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return "";
  return dateStr;
};

// 获取订单数据
const fetchOrders = async (params = {}) => {
  try {
    const response = await api.post("/torder/slectOrder", params);
    if (response.code === 200) {
      orders.value = response.data;
    } else {
      ElMessage.error(response.message || "获取订单数据失败");
    }
  } catch (error) {
    ElMessage.error("获取订单数据失败");
    console.error(error);
  }
};

// 搜索订单
const searchOrders = () => {
  const params = {
    startTime: searchForm.startTime,
    endTime: searchForm.endTime,
    ispaid: searchForm.ispaid,
  };
  fetchOrders(params);
};

// 重置搜索
const resetSearch = () => {
  searchForm.startTime = null;
  searchForm.endTime = null;
  searchForm.ispaid = null;
  fetchOrders();
};

// 打开编辑对话框
const openEditDialog = (order) => {
  editForm.orderid = order.orderid;
  editForm.creattime = order.creattime;
  editForm.endtime = order.endtime;
  editDialogVisible.value = true;
};

// 关闭对话框前的处理
const handleClose = (done) => {
  ElMessageBox.confirm("确认关闭？修改将不会保存")
    .then(() => {
      done();
    })
    .catch(() => {
      // 不关闭对话框
    });
};

// 更新订单
const updateOrder = async () => {
  if (!editForm.creattime || !editForm.endtime) {
    ElMessage.warning("请填写完整的起止时间");
    return;
  }

  try {
    const params = {
      orderid: editForm.orderid,
      creattime: editForm.creattime,
      endtime: editForm.endtime,
    };

    const response = await api.post("/torder/updateOrder", params);
    if (response.code === 200) {
      ElMessage.success("订单更新成功");
      editDialogVisible.value = false;
      fetchOrders();
    } else {
      ElMessage.error(response.message || "更新订单失败");
    }
  } catch (error) {
    ElMessage.error("更新订单失败");
    console.error(error);
  }
};

// 删除订单
const deleteOrder = (order) => {
  ElMessageBox.confirm(`确认删除订单 ${order.orderid} 吗？`, "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const params = {
          orderid: order.orderid,
        };

        const response = await api.post("/torder/deleteOrder", params);
        if (response.code === 200) {
          ElMessage.success("删除成功");
          fetchOrders();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        ElMessage.error("删除失败");
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.orders-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-item {
  margin-bottom: 20px;
}

.order-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}

.order-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.car-info {
  height: 100%;
  display: flex;
  align-items: center;
}

.car-image {
  width: 100%;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.car-img {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #909399;
  font-size: 30px;
}

.car-details h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 18px;
}

.car-details p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

.label {
  font-weight: bold;
  color: #909399;
  margin-right: 5px;
}

.order-details {
  height: 100%;
  display: flex;
  align-items: center;
}

.price {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.order-actions {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}

@media (max-width: 768px) {
  .order-card {
    margin-bottom: 15px;
  }

  .car-details h3 {
    font-size: 16px;
  }

  .car-details p {
    font-size: 12px;
  }
}
</style>
